package com.cskaoyan.realm;

import com.cskaoyan.service.AuthService;
import com.cskaoyan.vo.InfoVO;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @author LiaoLong
 * @date 2021-05-11 15:33
 */
@Component
public class AdminRealm extends AuthorizingRealm {
    @Autowired
    AuthService authService;

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        MallToken token = (MallToken) authenticationToken;
        String username = token.getUsername();
        // username要唯一
        String password = authService.queryPasswordByname(username);
        String credential = password;
        SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(username, credential, this.getName());
        return authenticationInfo;
    }


    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        String username = (String) principalCollection.getPrimaryPrincipal();
        //查询username对应的权限
        InfoVO infoVO = authService.queryByUsername(username);
        List<String> roles = infoVO.getRoles();
        List<String> perms = infoVO.getPerms();
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        // 给该用户添加权限
        authorizationInfo.addRoles(roles);
        authorizationInfo.addStringPermissions(perms);
        return authorizationInfo;
    }
}
